package com.edushare.common.dao;

import java.util.HashMap;
import java.util.List;

import org.apache.cayenne.query.SQLTemplate;

import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.OrgAliases;

public class OrgAliasesDAO extends CayenneBasedDAO {

	public OrgAliasesDAO(ORMInterface ormInterface) {
		super(ormInterface);
	}

	@SuppressWarnings("unchecked")
	public OrgAliases AddOrUpdate(String organizationNameAddedByUser) {
		
		OrgAliases orgAlias = null;
		SQLTemplate mysqlCaseSensitiveSelectQuery = new SQLTemplate(OrgAliases.class, 
																	"select * from ORG_ALIASES where binary ALIAS_NAME= #bind($aliasName 'VARCHAR')");
		HashMap hm = new HashMap();
		hm.put("aliasName", organizationNameAddedByUser);
		mysqlCaseSensitiveSelectQuery.setParameters(hm);
		List<OrgAliases> existingAliases = getDataContext().performQuery(mysqlCaseSensitiveSelectQuery);
		if(existingAliases!=null && existingAliases.size() > 0){
			orgAlias = existingAliases.get(0);
			orgAlias.setAliasUserCounts(orgAlias.getAliasUserCounts() + 1);
		}else{
			orgAlias = getDataContext().newObject(OrgAliases.class);
			orgAlias.setAliasName(organizationNameAddedByUser);
			orgAlias.setAliasUserCounts(1);
			orgAlias.setOrganization(null);//TODO: change this null to enable real organizations to map themselves
		}
		
		return orgAlias;
	}

}
